import Food from './Food'
import ScorePanel from './ScorePanel'
import Snake from './Snake'

class GameControl {
  snake: Snake
  food: Food
  scorePanel: ScorePanel

  // 方向
  direction: string = ''
  // 游戏是否结束
  isLive: boolean = true

  constructor() {
    this.snake = new Snake()
    this.food = new Food()
    this.scorePanel = new ScorePanel(10, 2)

    this.init()
  }

  init() {
    document.addEventListener('keydown', this.keydownHandler.bind(this))
    this.food.change()
    this.run()
  }

  keydownHandler(event: KeyboardEvent) {
    this.direction = event.key
  }

  // 控制移动
  run() {


    let X = this.snake.X
    let Y = this.snake.Y

    if (this.checkEat(X, Y)) {
      this.food.change()
      this.scorePanel.addScore()
      this.snake.addBody()
    }
    switch (this.direction) {
      case "ArrowUp":
        Y -= 10
        break;
      case "ArrowDown":
        Y += 10
        break;
      case "ArrowLeft":
        X -= 10
        break;
      case "ArrowRight":
        X += 10
        break
    }

    try {
      this.snake.X = X
      this.snake.Y = Y
    } catch (e: any) {
      alert(e.message + ' GAME OVER!')
      this.isLive = false
    }

    this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
  }

  // 是否吃到食物
  checkEat(X: number, Y: number): boolean {
    return X === this.food.X && Y === this.food.Y
  }
}

export default GameControl